//
//  OAuthViewController.swift
//  SK微博
//
//  Created by 姜胜凯 on 15/10/11.
//  Copyright © 2015年 姜胜凯. All rights reserved.
//

import UIKit
//import
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    //MARK:搭建界面

    private lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "登录界面"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        
    }
    
    //关闭界面
    func close(){
            SVProgressHUD.dismiss()
            dismissViewControllerAnimated(true, completion: nil)
    
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载授权页
        webView.loadRequest(NSURLRequest(URL: NetWorkTools.shareTools.oAuthUrl()))
    
       
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {}
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //重定向URL
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       //
        let urlstring = request.URL!.absoluteString
        if !urlstring.hasPrefix(NetWorkTools.shareTools.redirectUrl){
            print(urlstring)
            return true
        
        }
        print("判断参数")
        print(request.URL?.query)
        if let quer = request.URL?.query where quer.hasPrefix("code=") {
        print("获取授权码")
         //let r = (str as NSString).substringWithRange(NSMakeRange(2, 3))
          //substringFromIndex的作用：从某个位置开始到左后截取
            let code = quer.substringFromIndex("code=".endIndex)
            print(code)
            //加载Token
            loadAccessToken(code)
            
            
        }else{
        
        close()
        }
        
        return false
    }
    private func loadAccessToken (code : String)
    {
    
        NetWorkTools.shareTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil
                {
                SVProgressHUD.showErrorWithStatus("你的网络不给力")
                    //延迟一段时间在关闭
                    let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
                    dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
                        self.close()
                    })
                return
                }
            //字典转模型
            let count = UserAccount(dict :result!)
            count.saveAccount()
            print(count)
                        
            }
        
    }
    

}
